<?php
/**
 * Created by JetBrains PhpStorm.
 * User: root
 * Date: 13-12-25
 * Time: 上午11:03
 * To change this template use File | Settings | File Templates.
 */
namespace Common\Org\Email\Driver;
use Common\Org\Email\Email;
class EmailService extends Email {
    protected $config = array();

    private $FocusUser = null;
    private $FocusReceivers = array();
    private $FocusEmail = null;
    private $FocusTask = null;

    //初使化
    public function __construct($config) {
        if(!empty($config)) {
            $this->config = $config;
        }
    }

    private function setFocusReceivers($email) {
        if(!empty($email)) {
            $user = new \StdClass;
            $user->Email = $email;
            $this->FocusReceivers[] = $user;
        }
    }

    /**
     * 发送邮件方法
     */
    protected function send() {
        $SoapClient = new \SoapClient($this->config['url'], array('trace' => 1));

        $this->FocusUser   = new \StdClass;
        $this->FocusUser->Email = $this->config['account'];
        $this->FocusUser->Password = sha1($this->config['password']);

        foreach($this->email as $email) {
            $this->setFocusReceivers($email);
        }

        $this->FocusEmail = new \StdClass;
        $this->FocusEmail->Body = $this->body;
        $this->FocusEmail->IsBodyHtml = true;

        $this->FocusTask=new \StdClass;
        $this->FocusTask->TaskName = "sendTask:".date('Y-m-d H:i:s').'_'.rand(0,999999);
        $this->FocusTask->Subject = $this->them;
        $this->FocusTask->SenderName = $this->config['sender'];
        $this->FocusTask->SenderEmail = $this->config['send_email'];
        $this->FocusTask->ReplyName = $this->config['replier'];
        $this->FocusTask->ReplyEmail = $this->config['reply_email'];

        $this->FocusTask->SendDate = date("Y-m-d\TH:m:s");

        try {
            $result= $SoapClient->BatchSend(array("user"=>$this->FocusUser,"email"=>$this->FocusEmail,"task"=>$this->FocusTask,"receivers"=>$this->FocusReceivers));
        } catch (Exception $e) {
            throw_exception($e->getMessage());
        }

        $this->FocusReceivers = array();

        if($result->BatchSendResult=='success') {
            return true;
        } else {
            $this->error = $result->BatchSendResult;
            return false;
        }
    }
}